package messages;

import java.security.PrivateKey;
import java.security.PublicKey;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import security.crypto.AssimEncryption;
import utils.XmlSerializationUtils;

public class CertChallengeMessage implements Convertible{

	private static final long serialVersionUID = 1L;
	
	private String _cipheredChallenge;
	
	public CertChallengeMessage(){}
	
	public CertChallengeMessage(Integer clientChallenge, PublicKey serverKey){
		_cipheredChallenge = AssimEncryption.cipher(clientChallenge.toString(), serverKey);
	}
	
	public int getClientChallenge(PrivateKey serverPrivateKey){
		String challengeString = AssimEncryption.decipher(_cipheredChallenge, serverPrivateKey);
		
		return Integer.parseInt(challengeString);
	}

	public Element convertToCanonic(Document doc) {
		Element el = doc.createElement("CertChallengeMessage");

		if (_cipheredChallenge != null) {
			Element childEl = doc.createElement("CipheredChallenge");
			childEl.setTextContent(_cipheredChallenge);
			el.appendChild(childEl);
		}
		
		return el;
	}

	public Object convertFromCanonic(Element el) {
		this._cipheredChallenge = XmlSerializationUtils.getTextValue(el, "CipheredChallenge");
		return this;
	}

}
